<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @tree-load="treeLoad"
    >
      <!--
                 option  表格总配置属性
                 :table-loading="loading"  Boolean 表格等待框的控制
                 data    表格的数组数据
                 before-open  Function 打开前的回调，会暂停Dialog的打开function(done,type)，done用于关闭Dialog,type为当前窗口的类型
                 before-close  关闭前的回调，会暂停Dialog的关闭function(done,type)，done用于关闭Dialog,type为当前窗口的类型

                 :permission="permissionList" 允许 Array/Object/Function 表格多个按钮权限控制，采用函数方式可以精确到行控制

                -->
      <!--
                 @search-change="searchChange"  点击搜索后触发该事件(由于page分页信息和search搜索信息是sync修饰符，可以直接通过this.page和this.search拿到)
                 @search-reset="searchReset"          清空搜索回调方法
                 @selection-change="selectionChange"  当选择项发生变化时会触发该事件
                 @current-change="currentChange"      分页页码改变时会触发
                 @on-load="onLoad"                    首次加载数据、查询、翻页方法
                 @tree-load="treeLoad"                加载子树数据的方法，仅当 lazy 属性为true 时生效
                 -->
      <!-- .sync Vue修饰符 它会被扩展为一个自动更新父组件属性的 v-on 监听器 -->
      <!--
                 @row-update="rowUpdate" 编辑数据后确定触发该事件
                 @row-save="rowSave"     新增数据后点击确定触发该事件
                 @row-del="rowDel"       行数据删除时触发该事件
                -->
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.area_delete" @click="handleDelete">删 除 </el-button>
      </template>
      <!-- 新增子项操作 -->
      <template slot-scope="scope" slot="menu">
        <el-button type="text" icon="el-icon-circle-plus-outline" size="small" @click.stop="handleAdd(scope.row, scope.index)"
          >新增子项
          <!-- v-if="userInfo.role_name.includes('admin')" -->
        </el-button>
      </template>
      <template slot-scope="{ row }" slot="partCategories">
        <el-tag v-if="row.partCategoriesNames !== null">{{ row.partCategoriesNames }}</el-tag>
      </template>
      <template slot-scope="{ row }" slot="isLocator">
        <el-tag>{{ row.isLocator === false ? '否' : '是' }}</el-tag>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/admin/area';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getAreaTree } from '@/api/admin/area'; //加入请求树形结构的接口

export default {
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      form: {},
      query: {},
      parentId: 0,
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        lazy: true, //具备树形结构V向下展开的关键属性
        tree: true,
        height: 'auto',
        calcHeight: 20,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        menuWidth: 300, //弹框内字段宽度属性
        dialogWidth: 880, //弹框宽度属性
        dialogClickModal: false,
        indexLabel: '序号',
        column: [
          {
            label: '类型',
            // 仓库位，站台，线边区，入库待检区，出库拣货区，打包区域
            prop: 'areaType',
            search: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=area_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请选择区域类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '父级区域',
            prop: 'parentId',
            type: 'tree',
            dicData: [],
            hide: true,
            addDisabled: false,
            props: {
              label: 'title'
            },
            rules: [
              {
                required: false,
                message: '请输入父级区域',
                trigger: 'click'
              }
            ]
          },
          {
            label: '颜色标识',
            prop: 'color',
            type: 'color', //增加颜色选择器
            colorFormat: 'hex',
            // disabled: true,
            showAlpha: false
          },
          {
            label: '地址',
            prop: 'locationName',
            // bind: "location.name", //绑定对象层级中的值
            type: 'search',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择区域位置信息',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLocationCommonModal();
            }
          },
          {
            label: '层级',
            prop: 'level',
            type: 'number',
            rules: [
              {
                required: false,
                message: '请输入层级',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '可放容量',
            prop: 'capacity',
            rules: [
              {
                required: false,
                message: '请输入可放容量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '存储类别',
            prop: 'partCategories',
            type: 'tree',
            multiple: true, //是否多选
            // dicData: [], 增加了这个会使接口数据无效
            checkStrictly: true, //在显示复选框的情况下，是否严格的遵循父子不相互关联的做法
            dicUrl: '/api/mes-admin/part-category/tree',
            placeholder: '请选择 存储类别',
            props: {
              label: 'title',
              value: 'id'
            },
            rules: [
              {
                required: false,
                message: '请输入该区域可存储物料类别控制',
                trigger: 'click'
              }
            ]
          },
          // {
          //   label: '库存中心',
          //   prop: 'deptId',
          //   type: 'select',
          //   dicUrl: '/api/blade-system/dept/inventory-center',
          //   props: {
          //     label: 'deptName',
          //     value: 'id'
          //   },
          //   placeholder: '请选择 库存中心',
          //   rules: [
          //     {
          //       required: true,
          //       message: '请选择库存中心',
          //       trigger: 'blur'
          //     }
          //   ]
          // },
          {
            label: '库存中心',
            prop: 'inventoryId',
            type: 'select',
            dicUrl: '/api/mes-admin/inventory/list',
            props: {
              label: 'name',
              value: 'id'
            },
            placeholder: '请选择 库存中心',
            rules: [
              {
                required: true,
                message: '请选择库存中心',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '库位位置',
            prop: 'topMiddleBottom',
            type: 'select',
            dicData: [
              {
                label: '上',
                value: 'top'
              },
              {
                label: '中',
                value: 'middle'
              },
              {
                label: '下',
                value: 'bottom'
              }
            ],
            rules: [
              {
                required: false,
                message: '请输入库位位置',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '库位',
            prop: 'isLocator',
            type: 'switch', //开关的类型
            align: 'center',
            width: 100,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            value: 0,
            slot: true,
            rules: [
              {
                required: true,
                message: '请输入是否库位',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      data: [],
      treeParams: new Map() //懒加载参数,提交参数后重新刷新列表参数
    };
  },
  computed: {
    // Vuex状态管理机制,mapGetters辅助函数将store中映射到局部计算属性
    // 如下会转换成：
    // userInfo(){ return this.$store.state.userInfo }
    ...mapGetters(['userInfo', 'permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.area_add, false),
        viewBtn: this.vaildData(this.permission.area_view, false),
        delBtn: this.vaildData(this.permission.area_delete, false),
        editBtn: this.vaildData(this.permission.area_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    initData() {
      getAreaTree().then((res) => {
        const column = this.findObject(this.option.column, 'parentId');
        column.dicData = res.data.data;
      });
    },
    handleAdd(row) {
      this.parentId = row.id;
      const column = this.findObject(this.option.column, 'parentId');
      column.value = row.id;
      column.addDisabled = true;
      this.$refs.crud.rowAdd();
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 打开位置管理选择模态框
     */
    openLocationCommonModal() {
      this.modalName = 'locationModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择位置信息（双击进行选择）',
        url: '/api/mes-admin/location/page?status=0',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '地址名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '国家',
            prop: 'country',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '省份',
            prop: 'province'
          },
          {
            label: '城市',
            prop: 'city'
          }
        ]
      };
    },
    /**
     * 打开工作中心管理选择模态框
     */
    openWorkCenterCommonModal() {
      this.modalName = 'workCenterModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择库存中心管理信息（双击进行选择）',
        url: '/api/mes-admin/inventory/list',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '中心名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '中心编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '车间类型',
            prop: 'centerType'
          },
          {
            label: '是否库存中心',
            prop: 'isInventory'
          }
        ]
      };
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      if (this.modalName === 'locationModal') {
        this.form.locationId = this._get(rowData, 'id', '');
        this.form.locationName = this._get(rowData, 'name', '');
      } else if (this.modalName === 'workCenterModal') {
        this.form.deptId = this._get(rowData, 'id', '');
        this.form.deptName = this._get(rowData, 'name', '');
      }
    },
    rowSave(form, done, loading) {
      form.partCategories = form.partCategories.join(',');
      // form.availableCapacity = 77;
      add(form).then(
        () => {
          // 获取新增数据的相关字段(重新刷新加载数据列表)
          this.treeParams.forEach((item, key) => {
            const { tree, treeNode, resolve } = this.treeParams.get(key);
            this.treeLoad(tree, treeNode, resolve);
          });
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(form, index, done, loading) {
      form.partCategories = form.partCategories.join(',');
      update(form).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          // 刷新表格数据并重载
          this.data = [];
          this.parentId = 0;
          this.$refs.crud.refreshTable();
          this.$refs.crud.toggleSelection();
          // 表格数据重载
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    beforeOpen(done, type) {
      if (['add', 'edit'].includes(type)) {
        this.initData();
      }
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
          // hasOwnProperty()方法是Object的原型方法（实例方法），它定义在 Object.prototype 对象之上，所有 Object 的实例对象都会继承 hasOwnProperty() 方法。
          // hasOwnProperty()方法用来检测一个属性是否是对象的自有属性，而不是从原型链继承的。如果该属性是自有属性，那么返回 true，否则返回 false。
          // 换句话说，hasOwnProperty() 方法不会检测对象的原型链，只会检测当前对象本身，只有当前对象本身存在该属性时才返回 true。
          if (this.form.hasOwnProperty('partCategories')) {
            this.form.partCategories = this.form.partCategories.split(',');
          }
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.parentId = 0;
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.parentId = 0;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    beforeClose(done) {
      this.parentId = 0;
      const column = this.findObject(this.option.column, 'parentId');
      column.value = '';
      column.addDisabled = false;
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(this.parentId, Object.assign(params, this.query)).then((res) => {
        this.data = res.data.data;
        this.loading = false;
        this.selectionClear();
      });
    },
    treeLoad(tree, treeNode, resolve) {
      const parentId = tree.id;
      this.treeParams.set(parentId, { tree, treeNode, resolve });
      getList(parentId).then((res) => {
        resolve(res.data.data);
      });
    }
  }
};
</script>

<style></style>
